<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/5/5
 * Time: 16:54
 */

namespace app\shopping\model;

class Indent extends Commalltool{
    /**
     *  得到用户的订单
     */
    function getIndent($uid) {
        $sql = "SELECT * FROM sopp_indent WHERE uid='$uid' ORDER BY datetime DESC";
        $result = $this->mysql->selectSQLAll($sql);
        if (is_array($result)) {
            foreach ($result as $row) {
                $indent_id = !empty($row['indent_id']) ? $row['indent_id'] : false;
                if ($indent_id) {
                    $arr = $this->getIndentComm($indent_id);
                    $arr['accept_address'] = !empty($row['accept_address']) ? $row['accept_address'] : null;
                    $arr['accept_name'] = !empty($row['accept_name']) ? $row['accept_name'] : null;
                    $arr['accept_tel'] = !empty($row['accept_tel']) ? $row['accept_tel'] : null;
                    $arr['invoiceType'] = !empty($row['invoiceType']) ? $row['invoiceType'] : null;
                    $arr['modeOfPayment'] = !empty($row['modeOfPayment']) ? $row['modeOfPayment'] : null;
                    $arr['expressage'] = !empty($row['expressage']) ? $row['expressage'] : null;
                    $arr['remarks'] = !empty($row['remarks']) ? $row['remarks'] : $remarks = null;
                    $arr['taxNumb'] = !empty($row['taxNumb']) ? $row['taxNumb'] : $taxNumb = null;
                    $arr['datetime'] = !empty($row['datetime']) ? $row['datetime'] : $taxNumb = "未知";
                    $arr['indent_state'] = $this->getIndent_state($row['indent_state']);
                    $arr['indent_id'] = $indent_id;
                    $jsonArray[] = $arr;
                }
            }
            if (count($jsonArray) > 0) {
                return $jsonArray;//echoJson(1, );
            } else {
                return false;
            }
        } else {
            return false;

        }
    }

    /**
     *  得到用户的某一订单
     */
    function getIndentfromid($uid,$indent_id) {
        $sql = "SELECT * FROM sopp_indent WHERE uid='$uid' and indent_id='$indent_id' ORDER BY datetime DESC";
        $result = $this->mysql->selectSQLRow($sql);

        if($result){
            $indent_id = !empty($result['indent_id']) ? $result['indent_id'] : false;

            if ($indent_id) {
                $arr = $this->getIndentComm($indent_id);
                $arr['accept_address'] = !empty($result['accept_address']) ? $result['accept_address'] : null;
                $arr['accept_name'] = !empty($result['accept_name']) ? $result['accept_name'] : null;
                $arr['accept_tel'] = !empty($result['accept_tel']) ? $result['accept_tel'] : null;
                $arr['invoiceType'] = !empty($result['invoiceType']) ? $result['invoiceType'] : null;
                $arr['modeOfPayment'] = !empty($result['modeOfPayment']) ? $result['modeOfPayment'] : null;
                $arr['expressage'] = !empty($result['expressage']) ? $result['expressage'] : null;
                $arr['remarks'] = !empty($result['remarks']) ? $result['remarks'] : $remarks = null;
                $arr['taxNumb'] = !empty($result['taxNumb']) ? $result['taxNumb'] : $taxNumb = null;
                $arr['datetime'] = !empty($result['datetime']) ? $result['datetime'] : $taxNumb = "未知";
                $arr['indent_state'] = $this->getIndent_state($result['indent_state']);
                $arr['indent_id'] = $indent_id;
                //$jsonArray[] = $arr;

                return $arr;
            }
        }else{
            return false;
        }

    }

    /**
     *  得到用户的订单的商品
     */
    function getIndentComm($indent_id) {
        $sql = "SELECT * FROM sopp_indent_comm WHERE indent_id='$indent_id'  ORDER BY id DESC";
        $result = $this->mysql->selectSQLAll($sql);

        $jsonArray = array();
        $commCount = 0;
        $total_prices = 0;
        $total_integral = 0;
        if (is_array($result)) {

            foreach ($result as $row) {
                $comm_id = !empty($row['comm_id']) ? $row['comm_id'] : false;
                $comm_sort = !empty($row['comm_sort']) ? $row['comm_sort'] : false;
                $comm_quantity = !empty($row['comm_quantity']) ? (int) $row['comm_quantity'] : false;
                $comm_integral = !empty($row['comm_integral']) ? (int) $row['comm_integral'] : 0; //积分
                $comm_transaction_price = !empty($row['comm_transaction_price']) ? $row['comm_transaction_price'] : false;
                if ($comm_id && $comm_id && $comm_sort && $comm_quantity && $comm_transaction_price) {

                    $arr = $this->getItemComm($comm_sort, $comm_id);

                    $arr['comm_sort'] = $comm_sort;
                    $arr['comm_quantity'] = $comm_quantity;
                    $arr['comm_integral'] = $comm_integral; //

                    $arr['selected_attribute'] = $this->getselectedAttributeStr($row['selected_attribute']);

                    $arr['comm_transaction_price'] = $comm_transaction_price;
                    $jsonArray[] = $arr;
                    $commCount++;
                    $total_prices += (double) $comm_transaction_price * (int) $comm_quantity;
                    $total_integral += (int) $comm_integral * (int) $comm_quantity;
                }
            }
            if (count($jsonArray) > 0) {
                $total_prices = sprintf("%.2f", $total_prices); //强制保留两位小数
                return array('count' => $commCount, 'total_prices' => $total_prices, 'total_integral' => $total_integral, 'comm' => $jsonArray);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     *  加入订单
     * @param str $uid 账号
     * $comm_id 商品ID
     */
    function joinIndentComm($uid, $commInfo) {
        $datetime = date("Y-m-d H:i:s");
        $this->mysql->beginTransactionSQL(); //开始事务
        $indent_id = $this->getIndentID();
        if (!empty($indent_id)) {
            $accept_address = $_GET["accept_address"];
            $accept_name = $_GET["accept_name"];
            $accept_tel = $_GET["accept_tel"];
            $invoiceType = $_GET["invoiceType"];
            $modeOfPayment = $_GET["modeOfPayment"];
            $expressage = $_GET["expressage"];
            $remarks = $_GET["remarks"];
            $taxNumb = $_GET["taxNumb"];
            !empty($remarks) ? '' : $remarks = null;
            !empty($taxNumb) ? '' : $taxNumb = null;
            if (empty($accept_address) || empty($invoiceType) || empty($modeOfPayment) || empty($expressage)) {
                echo echoJson(-1, "加入订单失败,参数错误！");
                return;
            }
            $sql = "INSERT INTO sopp_indent (indent_id,uid,datetime,indent_state,accept_address,accept_name,accept_tel,invoiceType,modeOfPayment,expressage,remarks,taxNumb) "
                . "VALUES ('$indent_id','$uid','$datetime',1,'$accept_address','$accept_name','$accept_tel','$invoiceType','$modeOfPayment','$expressage','$remarks','$taxNumb')";
            if (mysql_query($sql)) {
                foreach ($commInfo as $comm) {
                    if (!$this->joinComm($uid, $comm, $indent_id)) {//把商品加入订单商品表并删除购物车
                        $this->mysql->rollbackTransactionSQL(); //滚回事务
                        echo echoJson(-1, "加入订单失败！-10");
                        return;
                    }
                }
            } else {
                $this->mysql->rollbackTransactionSQL(); //滚回事务
                echo echoJson(-1, "加入订单失败！-5");
                return;
            }
        } else {
            $this->mysql->rollbackTransactionSQL(); //滚回事务
            echo echoJson(-1, "加入订单失败！-6");
            return;
        }
        $this->mysql->submitTransactionSQL(); //提交事务
        echo echoJson(1, array('datetime' => $datetime, 'indent_id' => $indent_id));
    }

    /**
     *  把商品加入订单商品表并删除购物车
     */
    function joinComm($uid, $comm, $indent_id) {
        $comm_id = !empty($comm['comm_id']) ? $comm['comm_id'] : false;
        $comm_sort = !empty($comm['comm_sort']) ? $comm['comm_sort'] : false;
        $comm_present_quantity = !empty($comm['comm_present_quantity']) ? $comm['comm_present_quantity'] : 0;
        $indent_id = !empty($indent_id) ? $indent_id : false;
        if (!empty($comm_id) && !empty($indent_id) && !empty($comm_sort)) {
            $comm_quantity = !empty($comm['comm_quantity']) ? $comm['comm_quantity'] : 1;
            $comm_integral = !empty($comm['comm_integral']) ? $comm['comm_integral'] : 0;
            $selected_attribute = !empty($comm['selected_attribute']) ? $comm['selected_attribute'] : null;
            $comm_transaction_price = !empty($comm['comm_transaction_price']) ? $comm['comm_transaction_price'] : null;
            is_array($selected_attribute) ? $selected_attribute = json_encode($selected_attribute, JSON_UNESCAPED_UNICODE) : '';
            if (!empty($selected_attribute)) {
                $sql = "INSERT INTO sopp_indent_comm (indent_id,comm_id,comm_sort,comm_quantity,comm_present_quantity,selected_attribute,comm_transaction_price,comm_integral) VALUES "
                    . "('$indent_id','$comm_id','$comm_sort',$comm_quantity,$comm_present_quantity,'$selected_attribute',$comm_transaction_price,$comm_integral)";
            } else {
                $sql = "INSERT INTO sopp_indent_comm (indent_id,comm_id,comm_sort,comm_quantity,comm_present_quantity,comm_transaction_price,comm_integral) VALUES "
                    . "('$indent_id','$comm_id','$comm_sort',$comm_quantity,$comm_present_quantity,$comm_transaction_price,$comm_integral)";
            }
            if (!mysql_query($sql) || !$this->cancelShoppingCart($uid, $comm_id, $comm_sort)) {//删除和插入只要有一个执行失败就滚回(这里如果没从购物车加入的话本来是不用执行删除购物车的，因为购物车本来就没有)
                return false;
            } else {
                return true;
            }
        } else {//只要有一个执行失败就滚回
            return false;
        }
    }

    /**
     *  删除购物车
     * @param str $uid 账号
     */
    function cancelShoppingCart($uid, $comm_id, $comm_sort) {
        $sql = "DELETE FROM sopp_shoppingCart WHERE uid='$uid' AND comm_id='$comm_id' AND comm_sort='$comm_sort'";
        if (empty($comm_id) || empty($comm_sort) || !mysql_query($sql)) {
            return false;
        }
        return true;
    }

    /**
     *
     *  得到订单id
     */
    function getIndentID() {
        $sql = "SELECT indent_id FROM sopp_indent ORDER BY id DESC  LIMIT 1";
        $result = mysql_query($sql);
        if ($result) {
            $row = mysql_fetch_array($result);
            if ($row) {
                isset($row['indent_id']) ? $indent_id = $row['indent_id'] : $indent_id = "SD00000000000000";
                $indent_id = preg_replace('/\D/s', '', $indent_id); //去除字母
                $indent_id = 'SD' . $this->addLargeNumber($indent_id, '1');
                return $indent_id;
            } else {
                return $indent_id = "SD00000000000001";
            }
        } else {
            return false;
        }
    }

    /**
     *  删除订单
     * @param str $uid 账号
     */
    function cancelIndentComm($uid, $indent_id) {
        $indent_id_arr = explode('_', $indent_id);
        $indent_id_str = '';
        foreach ($indent_id_arr as $value) {
            $indent_id_str = $indent_id_str . "'" . $value . "',";
        }
        $indent_id_str = substr($indent_id_str, 0, strlen($indent_id_str) - 1);
        $sql = "DELETE FROM sopp_indent WHERE uid='$uid' AND indent_id in($indent_id_str)";
        if ($this->mysql->deleteSQL($sql)) {
            $this->getIndent($uid);
        } else {
            echo echoJson(0, "删除订单失败！");
        }
    }





    /**
     *  得到商品选择的属性的字符串
     * @param json $selected_attribute 数据库保存的选中属性
     */
    function getselectedAttributeStr($selected_attribute) {
        $selected_attributeArr = strToJsonArr($selected_attribute);
        if (count($selected_attributeArr) > 0) {
            $selected_attribute = "已选择：";
            foreach ($selected_attributeArr as $key => $value) {
                $selected_attribute .= $key . ": " . $value . "；   ";
            }
            return $selected_attribute;
        } else {
            return null;
        }
    }

    /**
     *  得到交易状态
     * @param str $indent_state 交易状态码
     */
    function getIndent_state($indent_state) {
//订单状态（1：待付款，2：待发货或已付款，3：待收货，4：交易成功，5：交易取消，6：交易关闭,7：待处理,8:已处理,9：已退款）
        switch ($indent_state) {
            case 1://待付款
                return "待付款";
            case 2://待发货
                return "待发货";
            case 3://待收货
                return "待收货";
            case 4://交易成功
                return "交易成功";
            case 5://交易取消
                return "交易取消";
            case 6://交易关闭
                return "交易关闭";
            case 7://待处理
                return "待处理";
            case 8://已处理
                return "已处理";
            case 9://已退款
                return "已退款";
            default:
                return "未知";
        }
    }

    /**
     * 超大数的运算
     * @param $a string 加数
     * @param $b string 被加数
     * @return string  运算结果
     */
    function addLargeNumber($a, $b) {
        $lenA = strlen($a);
        $lenB = strlen($b);
        $j = 0;
        $re = '';
        for ($inxA = $lenA - 1, $inxB = $lenB - 1; ($inxA >= 0 || $inxB >= 0); --$inxA, --$inxB) {
            $itemA = ($inxA >= 0) ? (int) $a[$inxA] : 0;
            $itemB = ($inxB >= 0) ? (int) $b[$inxB] : 0;
            $sum = $itemA + $itemB + $j;
            if ($sum > 9) {
                $j = 1;
                $sum = $sum - 10;
            } else {
                $j = 0;
            }
            $re = (string) $sum . $re;
        }
        if ($j > 0) {
            $re = (string) $j . $re;
        }
        return $re;
    }

    function ChangeIndentStatus($indent_id,$new_status){
        $sql = "update sopp_indent set indent_state='$new_status' where indent_id='$indent_id'";
        $result = $this->mysql->updateSQL($sql);

        return $result;
    }

    function getIndentStatus($indent_id){
        $sql = "select indent_state from sopp_indent where indent_id='$indent_id'";
        $result = $this->mysql->selectSQLRow($sql);

        return $result["indent_state"];
    }
}